const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
const bodyParser = require('body-parser');
const setupViewsRoutes = require('./routes/views');
const logger = require('./logger');
const {envConfig} = require('./../../config/application.config');
const connectMysql = require('./mysql/connect.js').connect;
const session = require('express-session');
const proxy = require('http-proxy-middleware');

function onUnhandledError(err) {
  try {
    logger.error(err);
  } catch (e) {
    console.log('LOGGER ERROR:', e); //eslint-disable-line no-console
    console.log('APPLICATION ERROR:', err); //eslint-disable-line no-console
  }
  process.exit(1);
}

function invalidReqHandling(err, req, res, next) {
  const ipaddr = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  logger.error(`IP: ${ipaddr} -- ${err.message}`);
  res.status(500).send('500');
}

process.on('unhandledRejection', onUnhandledError);
process.on('uncaughtException', onUnhandledError);

const setupAppRoutes =
  envConfig.nodeEnv === 'production' ? require('./middlewares/production') : require('./middlewares/development');

const app = express();

app.use(['/test', '/img'], proxy({target: 'https://cdn.facemagic888.com', changeOrigin: true, xfwd: true}));
app.set('env', process.env.NODE_ENV);
logger.info(`Application env: ${process.env.NODE_ENV}`);

app.use(logger.expressMiddleware);
app.use(bodyParser.json());
app.use(invalidReqHandling);
app.use(session({secret: 'recommand 128 bytes random string'}));
// application routes
setupViewsRoutes(app);
setupAppRoutes(app);
connectMysql();
app.use('/user', require('./routes/user'));
app.use('/api/*', require('./middlewares/sessionMiddleware'));
app.use('/api', require('./routes/api'));
app.use('/api/source', require('./routes/source'));
app.use('/api/common', require('./routes/common'));

let https_options;

if (envConfig.nodeEnv === 'production') {
  http.createServer(app).listen(envConfig.httpPort, () => {
    logger.info(`HTTP server is now running on port: ${envConfig.httpPort}`);
  });
} else {
  https_options = {
    key: fs.readFileSync('./.ssl/private.pem'),
    cert: fs.readFileSync('./.ssl/file.crt')
  };

  http.createServer(app).listen(envConfig.httpPort, () => {
    logger.info(`HTTP server is now running on port: ${envConfig.httpPort}`);
  });

  https.createServer(https_options, app).listen(envConfig.httpsPort, () => {
    logger.info(`HTTPS server is now running on port: ${envConfig.httpsPort}`);
  });
}
